import sounddevice as sd
import numpy as np

def record_audio(fs, duration):
    print("请击打桌面...")

    # 录制音频
    recording = sd.rec(int(fs * duration), samplerate=fs, channels=1)
    sd.wait()

    return recording

def calculate_intensity(recording):
    # 计算音频的声音强度（均方根值）
    intensity = np.sqrt(np.mean(recording**2))

    return intensity

def play_game():
    print("欢迎来到剪刀石头布游戏！")

    while True:
        # 录制音频
        fs = 44100  # 采样率
        duration = 1  # 录制时长（秒）
        recording = record_audio(fs, duration)

        # 计算声音强度
        intensity = calculate_intensity(recording)

        # 根据声音强度进行选择
        if intensity < 10000:
            user_choice = "石头"
        elif intensity < 40000:
            user_choice = "剪刀"
        else:
            user_choice = "布"

        # 打印选择结果和调试信息
        print(f"用户选择: {user_choice}")
        print(f"用户输入的力度（调试信息）: {int(intensity)}") 

        # 在这里根据需要添加其他游戏逻辑

        # 询问是否再玩一局
        play_again = input("是否再玩一局？(按下回车键继续，输入其他内容退出): ")
        if play_again.lower() != "":
            break

play_game()
